package com.kaishengit.web;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kaishengit.dao.CustomerDao;
import com.kaishengit.entity.User;
import com.kaishengit.service.Userservice;
import com.kaishengit.util.Stringutil;

public class UserServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	String  s = request.getParameter("s");
	Stringutil sg = new Stringutil();
	if(!sg.isNotEmpty(s)){
		toLogin(request,response);
	}else if("login".equals(s)){
		login(request,response);
	}else if("worker".equals(s)){
		chaworker(request,response);
		
	}
}
private void chaworker(HttpServletRequest request, HttpServletResponse response) throws IOException {
	String name = request.getParameter("name");
	name = new  String(name.getBytes("iso8859-1"),"utf-8");
	
	CustomerDao  cdao = new  CustomerDao();
	List<User>  list  = cdao.findName(name);
	response.setContentType("text/xml;setchar=utf-8");
	PrintWriter  out = response.getWriter();
	out.print("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
	out.print("<data>");
	for(User u : list){
		out.print("<recode>"+u.getName()+"</recode>");
		System.out.println(u.getName());
	}
	out.print("</data>");
	out.flush();
	out.close();
	
}
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
	HttpSession  session = request.getSession();
	String  name = request.getParameter("name");
	String  pwd = request.getParameter("pwd");
	
	Userservice  us = new Userservice();
	User user = us.findUser(name, pwd);
	if(user==null){
		request.getRequestDispatcher("WEB-INF/views/first.jsp").forward(request, response);
	}else if(user!=null){
		if(user.getRole().equals("admin")){
			
			session.setAttribute("admin", user);
			response.sendRedirect("product.html?s=chaxun");
		}else if(user.getRole().equals("worker")) {
			session.setAttribute("worker", user);
			response.sendRedirect("product.html?s=toaddworker");
		}
	}
	
}
private void toLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.getRequestDispatcher("WEB-INF/views/first.jsp").forward(request, response);
	
}
}
